//
//  SunStartVC.m
//  Xspcf
//
//  Created by sunshine on 16/11/8.
//  Copyright © 2016年 小小算盘. All rights reserved.
//

#import "SunStartVC.h"
#import "SunNavController.h"
#import "SunGesLoginVC.h"
#import "BeginOpenViewController.h"
#import "TouchIDVC.h"
#import "SunCycleProgress.h"
#import <LocalAuthentication/LocalAuthentication.h>

#undef Y
#define Y NY

@interface SunStartVC ()
{
    NSTimer *_timer;
    UIImageView *_img;
    SunCycleProgress *_progress;
    float _totalTime;
}
@end

@implementation SunStartVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatUI];
    [self requestToStart];
    // Do any additional setup after loading the view.
}

- (void)creatUI{
    _totalTime = self.time;
    _img = [[UIImageView alloc]init];
    [self.view addSubview:_img];
    self.view.backgroundColor = BACKGROUND;
    
    UIImageView *slogan = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"slogan"]];
    [self.view addSubview:slogan];
    [slogan setFrame:CGRectMake((SCREENWIDTH - 200)/2, SCREENHEIGHT - 80, 200, 31)];
    
    [_img setFrame:CGRectMake(0, 0, SCREENWIDTH, Y(540))];
    _img.contentMode = UIViewContentModeScaleAspectFill;
    _progress = [[SunCycleProgress alloc]initWithFrame:CGRectMake(0, 0, X(50), X(50))];
    [self.view addSubview:_progress];
    [_progress lt_setSize:CGSizeMake(X(50), X(50)) save:YES];
    [_progress lt_setRight:X(15) to:nil save:YES];
    [_progress lt_setTop:Y(30) to:nil save:YES];
    [_progress progressWithBGColor:LINE ProgressColor:[UIColor colorWithHexString:@"FC475A"] LineWidth:2 Start:-270 End:90 Width:X(50) Height:X(50)];
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
    UIButton *btn = [[UIButton alloc]init];
    [_progress addSubview:btn];
    [btn lt_All:SunEdgesMake(0, 0, 0, 0) save:YES];
    [btn setTitle:@"跳过" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor colorWithHexString:@"FC475A"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(next) forControlEvents:UIControlEventTouchUpInside];
    btn.titleLabel.font = FONT(15);
}

- (void)onTimer{
    self.time -= 0.05;
    [_progress setPercent:self.time / _totalTime duration:0 changeColor:nil];
    if (self.time <= 0) {
        [self next];
    }
    id temp = [UIApplication sharedApplication].delegate;
    AppDelegate *delegate = temp;
    if (!delegate.tab){
    }else {
        [_timer invalidate];
        _timer = nil;
    }
}

- (void)requestToStart{
    NSString *url = [NSString stringWithFormat:@"%@%@",KURL,API_START];
    [HttpRequest postURL:url withParam:nil success:^(id requestDic, NSString *msg) {
        [_img sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",KIMG,requestDic]] placeholderImage:nil completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            [self.view sendSubviewToBack:_img];
        }];
    } failure:^(NSString *errorInfo, int code) {
    }];
}

- (void)next{
    [_timer invalidate];
    _timer = nil;
    id temp = [UIApplication sharedApplication].delegate;
    AppDelegate *delegate = temp;
    if ([self isAppFirstRun]) {
        delegate.window.rootViewController = [[BeginOpenViewController alloc]init];
    }else{
        //登录密码
        LAContext* context = [[LAContext alloc] init];
        if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:nil]&&[[NSUserDefaults standardUserDefaults]boolForKey:kusetouchid]) {
            [self setTouchId];
        }else if ([[NSUserDefaults standardUserDefaults] boolForKey:@"IsSetGesture"]) {
            [self setLoginSecrit];
        }else {
            delegate.tab = [[SunTabController alloc]init];
            delegate.window.rootViewController = delegate.tab;
        }
    }
}

- (BOOL) isAppFirstRun{
    NSString *currentVersion = [[[NSBundle mainBundle] infoDictionary]
                                objectForKey:@"CFBundleShortVersionString"];
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    NSString *lastRunKey = [defaults objectForKey:@"last_run_version_key"];
    
    if (!lastRunKey) {
        [defaults setObject:currentVersion forKey:@"last_run_version_key"];
        return YES;
        // App is being run for first time
        //上次运行版本为空，说明程序第一次运行
        
    }

    return NO;
    
    
    
}
- (void)setTouchId{
    id temp = [UIApplication sharedApplication].delegate;
    AppDelegate *delegate = temp;
    TouchIDVC *vc = [[TouchIDVC alloc]init];
    SunNavController *navigation = [[SunNavController alloc]initWithRootViewController:vc];
    delegate.window.rootViewController = navigation;
}

- (void)setLoginSecrit{
    id temp = [UIApplication sharedApplication].delegate;
    AppDelegate *delegate = temp;
    SunGesLoginVC *vc = [[SunGesLoginVC alloc]init];
    SunNavController *navigation = [[SunNavController alloc]initWithRootViewController:vc];
    delegate.window.rootViewController = navigation;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
